import 'package:flutter/material.dart';

/*
  外面使用 
   runApp(StoreProvider<int,Actions>(
    child: App(),
    initialState: 99,
    reducer: reducer,
  ));


  var data =  MyData.of(context)

*/

typedef MyDataReducer<StateType, ActionType> = Function(
    StateType state, ActionType action);

class StoreProvider<StateType, ActionType> extends StatefulWidget {
  final child;
  final StateType initialState;
  final MyDataReducer<StateType, ActionType> reducer;
  StoreProvider({Key key, this.child, this.initialState, this.reducer})
      : super(key: key);

  @override
  _StoreProviderState createState() =>
      _StoreProviderState<StateType, ActionType>(
        child: child,
        state: initialState,
        reducer: reducer,
      );
}

class _StoreProviderState<StateType, ActionType> extends State<StoreProvider> {
  StateType state;
  final child;
  final MyDataReducer<StateType, ActionType> reducer;

  _StoreProviderState({this.child, this.state, this.reducer});

  void dispatch(action) {
    setState(() {
      state = reducer(state, action);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MyData(
      child: child,
      state: state,
      parent: this,
    );
    ;
  }
}

class MyData extends InheritedWidget {
  final state;
  final _StoreProviderState parent;

  MyData({
    Key key,
    child,
    this.state,
    this.parent,
  }) : super(key: key, child: child);

  static MyData of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<MyData>();
  }

  @override
  bool updateShouldNotify(MyData oldWidget) {
    return oldWidget.state != state;
  }
}
